package cn.itsource.pethome.system.role.service.impl;

import cn.itsource.pethome.base.query.BaseQuery;
import cn.itsource.pethome.system.role.domain.Role;
import cn.itsource.pethome.system.role.domain.RoleMenu;
import cn.itsource.pethome.system.role.domain.RolePermission;
import cn.itsource.pethome.system.role.mapper.RoleMapper;
import cn.itsource.pethome.system.role.service.IRoleService;
import cn.itsource.pethome.base.service.impl.IBaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xlh
 * @since 2023-02-01
 */
@Service
public class RoleServiceImpl extends IBaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void add(Role role) {
        super.add(role);
        addMenuAndPermission(role);
    }
    private void addMenuAndPermission(Role role) {
        //添加菜单的中间表
        List<Long> menus = role.getMenus();
        if (!menus.isEmpty()){
            menus.forEach(menuId->{
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuId);
                roleMapper.addRoleMenu(roleMenu);
            });
        }
        //添加权限的中间表
        List<Long> permissions = role.getPermissions();
        if(!permissions.isEmpty()){
            permissions.forEach(permissionId->{//循环的意思
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(role.getId());
                rolePermission.setPermissionId(permissionId);
                roleMapper.addRolePermission(rolePermission);
            });
        }
    }

    @Override
    public void update(Role role) {
        super.update(role);
        Long id = role.getId();
        roleMapper.delMenuByRoleId(id);
        roleMapper.delPermissionByRoleId(id);
        addMenuAndPermission(role);
    }

    @Override
    public void delete(Long id) {
        super.delete(id);
        roleMapper.delMenuByRoleId(id);
        roleMapper.delPermissionByRoleId(id);
    }

    @Override
    public List<Role> queryData(BaseQuery query) {
        List<Role> queryDatum = super.queryData(query);
        for (Role role :queryDatum)  {
            Long id = role.getId();
            role.setMenuList(roleMapper.getMenuByRoleId(id));
            role.setPermissionList(roleMapper.getPermissionByRoleId(id));
        }
        return queryDatum;
    }
}
